package com.camel.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.camel.core.controller.BaseCommonController;
import com.camel.core.entity.Result;
import com.camel.core.model.SysRole;
import com.camel.core.model.SysUser;
import com.camel.core.service.BaseCommonService;
import com.camel.core.utils.ResultUtil;
import com.camel.core.utils.SaTokenUtils;
import com.camel.system.service.SysRoleService;
import com.camel.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <角色注释>
 *
 * @author baily
 * @date 2019/7/5
 * @since 1.0
 **/
@RestController
@RequestMapping(("/sysRole"))
public class SysRoleController extends BaseCommonController<SysRole> {

    @Autowired
    private SysRoleService<SysRole> service;

    @Autowired
    private SaTokenUtils saTokenUtils;

    @Autowired
    private SysUserService<SysUser> userService;

    @Override
    public BaseCommonService<SysRole> getiService() {
        return service;
    }

    @GetMapping("/me")
    private Result me() {
        List<String> permits = saTokenUtils.getPermissionList(null);
        return ResultUtil.success(service.list(new QueryWrapper<SysRole>().in("role_name", permits)));
    }

    @Override
    public Result update(@RequestBody SysRole entity) {
        SysRole role = service.getById(entity.getRoleId());
        Result update = super.update(entity);
        if(!StringUtils.isEmpty(entity.getRoleName())) {
            if(update.isSuccess()) {
                List<SysUser> users = userService.list(new QueryWrapper<SysUser>().eq("role_name", role.getRoleName()));
                for (SysUser user : users) {
                    user.setRoleName(entity.getRoleName());
                }
                userService.updateBatchById(users);
            }
        }
        return update;
    }

    @Override
    public String getMouduleName() {
        return "角色";
    }
}

